const pool = require('../config/db');
const { v4: uuidv4 } = require('uuid');

const GroupChat = {
    async create({ name, user_ids }) {
        const group_id = uuidv4();
        const connection = await pool.getConnection();

        try {
            await connection.beginTransaction();

            await connection.query('INSERT INTO group_chats (group_id, name) VALUES (?, ?)', [group_id, name]);

            for (const user_id of user_ids) {
                await connection.query('INSERT INTO group_members (group_id, user_id) VALUES (?, ?)', [group_id, user_id]);
            }

            await connection.commit();
            return { group_id };
        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    },

    async createMessage({ group_id, user_id, content }) {
        const message_id = uuidv4();
        await pool.query(
            'INSERT INTO group_messages (message_id, group_id, user_id, content) VALUES (?, ?, ?, ?)',
            [message_id, group_id, user_id, content]
        );
        return { message_id };
    },

    async findMessages(group_id, limit = 20, offset = 0) {
        const [rows] = await pool.query(
            'SELECT gm.*, u.username FROM group_messages gm JOIN users u ON gm.user_id = u.user_id WHERE gm.group_id = ? ORDER BY gm.created_at DESC LIMIT ? OFFSET ?',
            [group_id, limit, offset]
        );
        return rows;
    }
};

module.exports = GroupChat;